package com.example.csetpp.service.impl;

import com.example.csetpp.pojo.vo.user.UniqueVisitorVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UniqueVisitorService {

    private static final String UNIQUE_VISITOR_PREFIX = "unique_visitors:daily:";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE; // yyyy-MM-dd

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public boolean add(String userId)
    {
        if (userId == null || userId.trim().isEmpty()) {
            return false; // 无效的用户ID不记录
        }

        String todayKey = getTodaysKey(LocalDate.now());

        Long added = stringRedisTemplate.opsForSet().add(todayKey, userId);
        log.info("{}+Redis记录用户+{}", todayKey, added);
        if (added != null && added > 0) {
            if (stringRedisTemplate.getExpire(todayKey) == null || stringRedisTemplate.getExpire(todayKey) < 0) {
                stringRedisTemplate.expire(todayKey, 30, TimeUnit.DAYS);
            }

            return true;
        }

        return false;
    }

    public UniqueVisitorVO getUV()
    {
        UniqueVisitorVO uniqueVisitorVO = new UniqueVisitorVO();
        uniqueVisitorVO.setToday(getTodaysUniqueVisitorCount());
        uniqueVisitorVO.setPastSevenDays(getUVForDays(7));
        uniqueVisitorVO.setPastFifteenDays(getUVForDays(15));
        return uniqueVisitorVO;
    }

    private long getUVForDays(Integer days)
    {
        long totalCount = 0L;
        LocalDate today = LocalDate.now();

        List<String> keysToFetch = new ArrayList<>();
        for (int i = 0; i < days; i++) {
            LocalDate date = today.minusDays(i);
            keysToFetch.add(getTodaysKey(date));
        }
        log.info("keys:{}", keysToFetch);
        for (String key : keysToFetch) {
            totalCount += stringRedisTemplate.opsForSet().size(key);
        }


        return totalCount;
    }

    public long getTodaysUniqueVisitorCount() {
        String todayKey = getTodaysKey(LocalDate.now());
        Long count = stringRedisTemplate.opsForSet().size(todayKey);
        return count != null ? count : 0;
    }


    private String getTodaysKey(LocalDate date) {
        return UNIQUE_VISITOR_PREFIX + date.format(DATE_FORMATTER);
    }


}
